package com.tanhua.dubbo.server.service;

import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/1 23:58
 */

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Async   //异步开线程执行方法
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId) {

        try {
            //首先查询好友列表：
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> users = mongoTemplate.find(query, Users.class);

            if (users.isEmpty()) {
                //没有好友，也返回ok;
                return CompletableFuture.completedFuture("ok");
            }

            //users集合是 ： Users(id=5fae46737e529926e45ec122, userId=1, friendId=57, date=1605256819260)....这种
            //设置时间线：
            TimeLine timeLine;
            for (Users user : users) {
                timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setUserId(user.getUserId());
                timeLine.setPublishId(publishId);
                timeLine.setDate(System.currentTimeMillis());
                //写如数据：
                mongoTemplate.save(timeLine, "quanzi_time_line_" + user.getFriendId());
            }
            return CompletableFuture.completedFuture("ok");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发布动态失败,publish= " + publishId, e);
            //TODO  事务回滚
        }
        return CompletableFuture.completedFuture("error");


    }
}
